<template>
  <div>
    <el-upload
      class="upload-demo"
      :action="action"
      :headers="formHeader"
      :data="formData"
      name="img"
      :show-file-list="true"
      :limit='1'
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
      :on-remove="handleRemove">
      <el-button size="small" type="primary">点击上传</el-button>
     <div class="el-upload__tip" slot="tip" v-if="tip">{{tip}}</div>
    </el-upload>
  </div>
</template>

<script>
import { getToken } from '@/utils/token'
import md5 from 'js-md5'
import { endecrypt } from '@/utils/aes_endecrypt'

export default {
  name: 'UploadOne',
  props: {
    formData:{
      type: Object,
      default: {}
    },
   /* showUrl:{
      type: String,
      default: ''
    },*/
    tip:{
      type: String,
      default: ''
    },
  },
  data() {
    return {
      action: process.env.VUE_APP_BASE_API + "common.upload/upload_one.html",
      formHeader: {
      	token: getToken(),
      	apiKey: process.env.VUE_APP_BASE_API_KEY,
      },
     /* formData: {
      	dir_type: "",//上传路径
        file_name: "",//上传文件名(固定)
        allow_type: "",//允许上传的文件后缀（多个逗号隔开）
        file_size: "",//允许上传文件大小
      },
      tip: '',//提示文字*/
      formUrl: '', //form文件url
      formSize: 0, //form文件大小
    }
  },
  methods: {
    //上传文件之前的钩子
    beforeUpload(file) {
      //formHeader 参数
      //请求时间戳
      let timeStamp = Math.round(new Date() /1000)
      this.formHeader.timeStamp = timeStamp
      this.formHeader.sign = md5(process.env.VUE_APP_BASE_API_KEY+process.env.VUE_APP_BASE_API_SECRET+timeStamp).toUpperCase()

      //判断上传类型?

      //判断文件大小
      /*const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;*/
    },
    // 图片上传成功
    handleSuccess(response, file) {
      //解密
      if(typeof(response.datas) == 'string'){
        response.datas = endecrypt(response.datas, true)
      }
      if (response.code == 200) {
        this.formUrl = response.datas.file_name;
        this.formSize = file.size;
        //文件大小 file.size
        this.$emit('uploadCallBack', {fileName: this.formUrl, fileDomain: response.datas.img_root, size: file.size});
      } else {
        this.$message(response.datas.error);
      }
    },
    // 删除
    handleRemove(file,fileList) {
      this.formUrl = '';
      this.$emit('uploadCallBack', {fileName: '',size: 0});
    }
  }
}
</script>

<style type="text/css">


</style>
